package com.dnzx.controller.common;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.io.File;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.dnzx.framework.result.ResultUtils;
import org.dnzx.framework.result.domain.Result;
import org.dnzx.framework.upload.LocalUploadUtil;
import org.dnzx.framework.upload.fastdfs.FastDFSClient;
import org.dnzx.util.GlobalName;
import org.dnzx.util.MyStringUtils;
import org.dnzx.util.PropertyUtil;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>附件上传工具类</p>
 * @Package com.dnzx.base.controller.attachment
 * @author Steven
 * @e-mail zsq.471214943@163.com
 * @date 2018-07-25 11:57:30
 * @version V1.0
 */

@RestController
@RequestMapping("/attachment")
@Api(value = "/attachment",description = "附件上传",produces = MediaType.MULTIPART_FORM_DATA_VALUE)
public class AttachmentController {

    /**
     * <p>
     *  说明：图片上传方法
     * </p>
     * @param urlfile  MultipartFile 要上传的图片
     * @return org.dnzx.framework.result.domain.Result
     * @throws
     * @auth Steven
     */
	@PostMapping(value="/upload")
    @ApiOperation(value = "/",notes = "新增报表规格配置",httpMethod = "POST")
	public Result upload(MultipartFile urlfile) {
	    if(urlfile.isEmpty()){
	        return ResultUtils.returnError("上传图片失败");
        }
        // 获取图片的后缀,统一用小写
        boolean isFile = StringUtils.endsWithAny(
                StringUtils.lowerCase(urlfile.getOriginalFilename()), new String[] { ".png",
                        ".jpg", ".jpeg", ".bmp", ".gif" });
        if(!isFile){
            return ResultUtils.returnError("图片格式不正确,上传图片失败");
        }
        String fileName;
	    try{
            fileName= FastDFSClient.uploadFileWithMultipart(urlfile);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtils.returnError("图片上传失败");
        }
		return ResultUtils.returnSuccess("图片上传成功",fileName);
	}

	private String getOppositeFilePath(Integer pathCode){
		return GlobalName.getInstance().getProperty("imgPath")+"/upload/product/";
	}

    /**
     * <p>
     *  说明：本地图片上传方法
     * </p>
     * @param urlfile  MultipartFile 要上传的图片
     * @param pathCode Integer 图片存储路径code
     * @return org.dnzx.framework.result.domain.Result
     * @throws
     * @auth Steven
     */
    @PostMapping(value="/uploadLocal")
    @ApiOperation(value = "/uploadLocal",notes = "本地图片上传",httpMethod = "POST")
    public Result uploadLocal(MultipartFile urlfile,
                         Integer pathCode) {
        if(urlfile.isEmpty()){
            return ResultUtils.returnError("上传图片失败");
        }
        String filePath = getOppositeFilePath(pathCode);
        // 获取图片的后缀,统一用小写
        boolean isFile = StringUtils.endsWithAny(
                StringUtils.lowerCase(urlfile.getOriginalFilename()), new String[] { ".png",
                        ".jpg", ".jpeg", ".bmp", ".gif" });
        if(!isFile){
            return ResultUtils.returnError("图片格式不正确,上传图片失败");
        }

        String fileName= MyStringUtils.getUploadImg()+"."
                + StringUtils.substringAfter(urlfile.getOriginalFilename(), ".");
        try{
            LocalUploadUtil.uploadImage(urlfile,fileName,filePath);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtils.returnError("图片上传失败");
        }
        return ResultUtils.returnSuccess("图片上传成功",fileName);
    }
    
    @PostMapping("/fileUpload")
	@ApiOperation(value="/fileUpload",notes="上传文件（图片和其他格式都可以）",httpMethod="POST",produces=MediaType.APPLICATION_JSON_VALUE)
    public Result fileUpload(MultipartFile uploadFile) {
        String fileUri = null;
        try {
        	if (null != uploadFile) {
                // 服务器上保存文件的目录
                String pathRoot = PropertyUtil.getProperty("file.path");
                // 获取上传文件的原文件名
                String fileName = uploadFile.getOriginalFilename();
                String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
                String newFileName = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
                String nextPath = fileType;
                String savePath = pathRoot + nextPath;
                String filePath = nextPath + "/" + newFileName;
                File fileDir = new File(savePath);
                // 如果目录不存在，新建文件目录
                if (!fileDir.exists()) {
                    fileDir.mkdirs();
                }
                // 将最终的上传绝对目录返回
                uploadFile.transferTo(new File(savePath, newFileName)); // 上传文件
                fileUri = PropertyUtil.getProperty("file.uri") + filePath;// 返回文件URL
            }
            return ResultUtils.returnSuccess("SUCCESS", fileUri);
        } catch (Exception e) {
            return ResultUtils.returnError("ERROR >>> " + e.getMessage());
        }

    }
}
